package com.example.chatbackend.controller;

import com.example.chatbackend.dto.MoodDtos.MoodItemResponse;
import com.example.chatbackend.dto.MoodDtos.MoodSaveRequest;
import com.example.chatbackend.dto.MoodDtos.MoodSaveResponse;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/moods")
public class MoodController {
    private final Map<String, List<StoredMood>> storage = new ConcurrentHashMap<>();
    private final AtomicLong idGen = new AtomicLong(1);

    @PostMapping
    public MoodSaveResponse save(@RequestBody MoodSaveRequest dto) {
        StoredMood mood = new StoredMood();
        mood.id = idGen.getAndIncrement();
        mood.sessionId = dto.getSessionId();
        mood.tags = dto.getTags();
        mood.note = dto.getNote();
        mood.timestamp = dto.getTimestamp() > 0 ? dto.getTimestamp() : Instant.now().toEpochMilli();
        storage.computeIfAbsent(mood.sessionId, k -> new ArrayList<>()).add(mood);
        return new MoodSaveResponse(true);
    }

    @GetMapping
    public List<MoodItemResponse> list(@RequestParam String sessionId) {
        List<StoredMood> items = storage.getOrDefault(sessionId, List.of());
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
        return items.stream()
                .map(m -> new MoodItemResponse(
                        m.id,
                        fmt.format(Instant.ofEpochMilli(m.timestamp)),
                        String.format("%s %s", String.join(" / ", m.tags == null ? List.of() : m.tags), m.note == null ? "" : m.note)
                ))
                .collect(Collectors.toList());
    }

    static class StoredMood {
        long id;
        String sessionId;
        List<String> tags;
        String note;
        long timestamp;
    }
}


